package com.kgm.service;

import com.spring.BeanPostProcessor;
import com.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        if (beanName.equals("userService")) {
            ((UserServiceImpl) bean).setBeanName(beanName);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if (beanName.equals("userService")) {
            // Proxy.newProxyInstance的三个参数示意:
            // 1,类加载器(好像是任意一个类加载器都可以,因为类加载器对象可以加载任何类)
            // 2,当前要被代理的对象集成的接口列表
            // 3,代理方法具体实现[代码的代理就是在这里实现的]
            Object proxyBean = Proxy.newProxyInstance(this.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("执行了代理方法：" + method.getName());
                    return method.invoke(bean, args);
                }
            });
            return proxyBean;
        }
        return bean;
    }
}
